<?php
// +----------------------------------------------------------------------
// | Description: 合同
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com 
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\Record;
use app\crm\model\Receivables;
use Exception;
use think\Hook;
use think\Request;
use think\Db;

class Contract extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function _initialize()
    {
        $action = [
            'permission' => [''],
            'allow' => ['check', 'revokecheck', 'product', 'workindex', 'okindex', 'isend', 'picking', 'roam','getRefundDetail']
        ];
        Hook::listen('check_auth', $action);
        $request = Request::instance();
        $a = strtolower($request->action());
        if (!in_array($a, $action['permission'])) {
            parent::_initialize();
        }
    }

    /**
     * 合同列表
     * @return
     * @author Michael_xu
     */
    public function index()
    {
        $contractModel = model('Contract');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        /*$param['is_ok'] =0;
        $param['check_status'] =["<>",2];*/
        $data = $contractModel->getDataList($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 工单库
     * @return
     * @author Michael_xu
     */
    public function workindex()
    {
        $contractModel = model('Contract');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $param['check_status'] = 2;
        $param['is_ok'] = 0;
        $data = $contractModel->getDataList($param, 1);
        return resultArray(['data' => $data]);
    }

    /**
     * 完结库
     * @return
     * @author Michael_xu
     */
    public function okindex()
    {
        $contractModel = model('Contract');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $group = db('admin_access')->where(['user_id' => $userInfo["id"], "group_id" => 1])->find();
        if (empty($group)) {
            $param['owner_user_id'] = $userInfo['id'];
        }
        $param['is_ok'] = 1;
        $data = $contractModel->getDataList($param, 2);
        return resultArray(['data' => $data]);
    }
    //2023-10-16 lina 新增 start
    //获取退款单详情内容
    // public function getRefundDetail(){
    //     $param = $this->param;
    //     $data=db("crm_finance")->alias("f")
    //         ->join("crm_customer customer","customer.customer_id=f.customer_id")
    //         ->join("crm_contract_product cp","cp.contract_id=f.contract_id")
    //         ->join("crm_product p","p.product_id=cp.product_id")
    //         ->join("admin_user user","user.id=f.create_user_id")
    //         ->where(["f.relation_id"=>$param["id"],"f.order_type"=>"退款"])
    //         ->field("f.department,user.realname,f.order_sn,customer.name customer_name,p.name product_name,f.should_refund_money,f.calculate,f.calculate_way,f.recover_money,f.refund_money,cp.subtotal,f.remarks,f.check_status,f.created_time")
    //         ->find();
    //     //审批记录
    //     $data["examineRecord"]=Db::name("admin_examine_record")->alias("r")
    //         ->join("admin_user admin","admin.id=r.check_user_id","left")
    //         ->where(["r.types"=>"oa_examine","r.types_id"=>$param["id"]])
    //         ->order("r.record_id asc")
    //         ->field("admin.realname,r.status,FROM_UNIXTIME(r.check_time,'%Y-%m-%d %H:%i') as check_time,r.content")
    //         ->select();
    //     return resultArray(['data' => $data]);
    // }
    public function getRefundDetail(){
        $param = $this->param;
        $data=db("crm_finance")->alias("f")
            ->join("crm_customer customer","customer.customer_id=f.customer_id")
            ->join("crm_contract_product cp","cp.contract_id=f.contract_id")
            ->join("crm_product p","p.product_id=cp.product_id")
            ->join("admin_user user","user.id=f.create_user_id")
            ->where(["f.relation_id"=>$param["id"],"f.order_type"=>"退款"])
            ->field("f.department,user.realname,f.order_sn,customer.name customer_name,p.name product_name,f.should_refund_money,f.calculate,f.calculate_way,f.contract_id,f.recover_money,f.refund_money,f.remarks,f.check_status,f.created_time")
            ->find();
        //审批记录
        $data["examineRecord"]=Db::name("admin_examine_record")->alias("r")
            ->join("admin_user admin","admin.id=r.check_user_id","left")
            ->where(["r.types"=>"oa_examine","r.types_id"=>$param["id"]])
            ->order("r.record_id asc")
            ->field("admin.realname,r.status,FROM_UNIXTIME(r.check_time,'%Y-%m-%d %H:%i') as check_time,r.content")
            ->select();

        $contractModel = new \app\crm\model\Contract();
        $contractData = $contractModel->getDataById($data["contract_id"]);
        $calculate=db("crm_finance")->where(["order_type"=>"退款","contract_id"=>$contractData['contract_id'],"check_status"=>2])->sum("calculate");//退款退回业绩
        $refund_money=db("crm_finance")->where(["order_type"=>"退款","contract_id"=>$contractData['contract_id'],"check_status"=>2])->sum("refund_money");//实际退款金额
        $data['performance']=bcadd($contractData["performance"],$calculate,2);
        $data["money"]=bcsub($contractData['receivablesMoney']["lasahmMoney"],$refund_money,2);
        return resultArray(['data' => $data]);
    }
    /**
     * 管家二次确认是否完结
     * */
    public function isend()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $contractModel = new \app\crm\model\Contract();
        $contract = $contractModel->where(["contract_id" => $param['contract_id']])->find();
        if (!isset($param["contract_id"])) return resultArray(['error' => '合同id为空']);
        // 判断账号是否拥有管家身份
        $butler_group = db('admin_access')->where(['user_id' => $userInfo['id'], "group_id" => "32"])->find();
        if ($contract["butler_id"] != $userInfo["id"] && !$butler_group) {
            return resultArray(['error' => '您不可操作']);
        }
        $contract->save(["is_ok" => 1]);//修改合同状态为已完结
        return resultArray(['data' => "已流转至完结库"]);
    }

    /**
     * 待办数据统计
     * */
    public function deputystat()
    {
        $param = $this->param;
        $data = Record::getDeputystat($param);
        return resultArray(['data' => $data]);
    }
    //2023-10-16 lina 新增 end
    //2023-10-27 lina 新增 start
    /**
     * 管家捡取
     * */
    public function picking()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $contractModel = model('Contract');
        $isButler = db('admin_access')->where(["user_id"=>$userInfo["id"],"group_id"=>32])->find();//管家
        if(!$isButler) return resultArray(['error' => "工单只能管家捡取！"]);
        $contract_ids = $param['contract_id'];
        if (!$contract_ids || !is_array($contract_ids)) {
            return resultArray(['error' => '请选择需要捡取的工单']);
        }
        $errorMessage = [];
        foreach ($contract_ids as $k => $v) {
            $dataName = $contractModel->where(['contract_id' => $v])->find();//->value('name');
            $data = ["state" => 2, "butler_id" => $userInfo["id"], "butler_time" => time()];
            $resCustomer = $contractModel->where(['contract_id' => $v, "state" => 1])->update($data);
            if (!$resCustomer) {
                $errorMessage[] = '工单《' . $dataName["name"] . '》捡取失败，错误原因：数据出错；';
                continue;
            }
        }
        if (!$errorMessage) {
            return resultArray(['data' => '捡取成功']);
        } else {
            return resultArray(['error' => $errorMessage]);
        }
    }
    //2023-10-27 lina 新增 end

    //2023-12-19 lina 新增 start
    /**
     * 管家点击流转到记账
     * */
    public function roam()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $contractModel = model('Contract');

        if (!isset($param['contract_id'])) {
            return resultArray(['error' => '请选择流转的工单']);
        }
        $contract = $contractModel->where(["contract_id" => $param['contract_id']])->find();
        if (empty($contract)) {
            return resultArray(['error' => '工单不存在']);
        }
        if ($contract["is_accounting"] == 1) {
            return resultArray(['error' => '工单已流转到记账板块']);
        }
        if ($contract["butler_id"] != $userInfo["id"]) {
            return resultArray(['error' => '您不可流转该记账工单']);
        }
        $price = 0;
        $accountingModel = model('Accounting');
        $price = $accountingModel->monthlyAgencyPrice($contract);
        $contract->allowField(true)->save(["is_accounting" => 1, "monthly_agency_price" => $price, "state" => 3]);
        return resultArray(['data' => '成功']);
    }

    //2023-12-19 lina 新增 end

    /**
     * 添加合同
     * @param
     * @return
     * @author Michael_xu
     */
    public function save()
    {
        $contractModel = model('Contract');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $examineStepModel = new \app\admin\model\ExamineStep();
        $param['create_user_id'] = $userInfo['id'];
        $param['owner_user_id'] = $userInfo['id'];
        /*----------------------------处理产品确认信息赋值start--------------------------------*/
        $param["crm_ddisob"]="新签";//只有记账订单才有续费单，其他订单默认都是新签单
        $param["state"]=1;//默认待捡取
        $param["crm_yfvcld"]=0;//记账单量默认为0
        $param["crm_grvgkz"]=0;//服务期数默认为0
        $fieldList=$param["product"][0]["fieldList"];//产品确认函信息
        if(isset($fieldList)){
            foreach ($fieldList as $list){
                if($list["title"]=="服务期数"){
                    $param["crm_grvgkz"]=$list["value"];
                }
                if($list["title"]=="服务公司"){
                    $param["name"]=$list["value"];
                }
                if($list["title"]=="记账单量"){
                    $param["crm_yfvcld"]=$list["value"];
                }
                if($list["title"]=="记账类型"){
                    $param["crm_ddisob"]=$list["value"];
                }
                if($list["title"]=="原销售"){
                    $param["crm_oonnxn"]=$list["value"];
                }
            }
        }
        /*----------------------------处理产品确认信息赋值end--------------------------------*/
        //审核判断（是否有符合条件的审批流）
        $examineFlowModel = new \app\admin\model\ExamineFlow();
        if (!$examineFlowModel->checkExamine($param['create_user_id'], 'crm_contract')) {
            return resultArray(['error' => '暂无审批人，无法创建']);
        }
        //添加审批相关信息
        $examineFlowData = $examineFlowModel->getFlowByTypes($param['create_user_id'], 'crm_contract');
        if (!$examineFlowData) {
            return resultArray(['error' => '无可用审批流，请联系管理员']);
        }
        $param['flow_id'] = $examineFlowData['flow_id'];
        // if ($param["crm_wvgjii"] == "记账" && (empty($param["crm_grvgkz"]) || $param["crm_grvgkz"] <= 0)) {
        //     return resultArray(['error' => '请输入服务期数']);
        // }
        //获取审批人信息
        if ($examineFlowData['config'] == 1) {
            //固定审批流
            $nextStepData = $examineStepModel->nextStepUser($userInfo['id'], $examineFlowData['flow_id'], 'crm_contract', 0, 0, 0);
            $next_user_ids = arrayToString($nextStepData['next_user_ids']) ?: '';
            $check_user_id = $next_user_ids ?: [];
            $param['order_id'] = 1;
        } else {
            $check_user_id = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
        }
        if (!$check_user_id) {
            return resultArray(['error' => '无可用审批人，请联系管理员']);
        }
        if ($param["receivables_money"] > $param["total_price"] ) {
            return resultArray(['error' => '回款金额不能大于订单金额']);
        }
        if ($param["receivables_money"] < 0) {
            return resultArray(['error' => '回款金额不能小于0']);
        }
        //核定成本为负
        if($param["crm_oeseng"] < 0 && $param["crm_wvgjii"]!="特批"){
            return resultArray(['error' => '核定成本不能小于0']);
        }
        if ($param["receivables_money"] < $param["crm_oeseng"] && $param["crm_wvgjii"]!="特批") {
            return resultArray(['error' => '核定成本不能超过回款金额']);
        }
        $param['check_user_id'] = is_array($check_user_id) ? ',' . implode(',', $check_user_id) . ',' : $check_user_id;
        //流程审批人
        // $flow_user_id = $examineFlowModel->getUserByFlow($examineFlowData['flow_id'], $param['create_user_id']); 
        // $param['flow_user_id'] = $flow_user_id ? arrayToString($flow_user_id) : '';
        if ($contractModel->createData($param)) {
            return resultArray(['data' => '添加成功']);
        } else {
            return resultArray(['error' => $contractModel->getError()]);
        }
    }

    /**
     * 合同详情
     * @param
     * @return
     * @author Michael_xu
     */
    public function read()
    {
        $contractModel = model('Contract');
        $userModel = new \app\admin\model\User();
        $param = $this->param;
        $userInfo = $this->userInfo;
        $data = $contractModel->getDataById($param['id']);

        $receivablesModel = new \app\crm\model\Receivables();
        $moneyInfo = $receivablesModel->getMoneyByContractId($data['contract_id']);

        //退款退回业绩
        $calculate=db("crm_finance")->where(["order_type"=>"退款","contract_id"=>$data['contract_id'],"check_status"=>2])->sum("calculate");
        //实际退款金额(不含追回金额)
        $should_refund_money=db("crm_finance")->where(["order_type"=>"退款","contract_id"=>$data['contract_id'],"check_status"=>2])->sum("should_refund_money");
        //总退款金额(含追回金额)
        $refund_money=db("crm_finance")->where(["order_type"=>"退款","contract_id"=>$data['contract_id'],"check_status"=>2])->sum("refund_money");

        //月度服务费
        $data['crm_month_price']=bcdiv(($data["money"]-$data["cost_production"]-$moneyInfo["hsOeseng"]),$data["crm_grvgkz"],2);
        // 总成本(初始成本+成本调整)
        $crm_oeseng = db("crm_finance")->where(["contract_id"=>$data["contract_id"],"check_status"=>2])->sum("crm_oeseng");
        // 变更的成本
        $change_crm_oeseng = db("crm_finance")->where(["contract_id"=>$data['contract_id'],"order_type"=>"成本变更","check_status"=>["in",[0,1,2]]])->sum("crm_oeseng");

        /****************************1、核定成本计算***************************/
        // 退回成本
        $th_crm_oeseng = bcadd($should_refund_money,$calculate,2);
        // 核定成本 = 现有金额（回款单核定成本+成本调整增减成本）-退回成本（退款金额[仅“金额”，不含追回金额]-退回业绩）
        $data['crm_oeseng'] = bcsub($crm_oeseng,$th_crm_oeseng,2);

        /****************************2、业绩计算*******************************/
        // 业绩=现有金额（回款单核算业绩+成本调整增减业绩）-退回业绩（退款申请）
        $performance = bcsub($data["performance"],$change_crm_oeseng,2);
        $data["performance"] = bcadd($performance,$calculate,2);

        /****************************3、已开票、可开票金额***********************/
        if($data["crm_upqdbn"]=="正常开票"){//正常开票开回款金额
            $data["invoice_money"] = db("crm_finance")->where(["contract_id"=>$data["contract_id"],"order_type"=>"回款","check_status"=>2])->sum("money");//可开票金额
        }else{
            $data["invoice_money"]=$data["money"];//可开票金额=合同订单金额
        }

        // 已开票金额
        $data["invoice_used_money"]=db("crm_invoice_detail")->where(["contract_id"=>$data["contract_id"],"status"=>["elt","2"]])->sum("money");//已经开票金额
        // 可开票金额 = 回款金额-已开票金额-退款金额
        $sub_invoice_money =  bcadd($refund_money,$data["invoice_used_money"],2);
        $data["invoice_money"] = bcsub($data["invoice_money"],$sub_invoice_money,2);

        /*******************************4、已报销、可报销***********************/
        //已报销金额
        $data["expence_used_money"] = db("crm_expence_detail")->alias("d")
            ->join("crm_expence e","d.expence_id=e.id")
            ->where(["d.contract_id"=>$data["contract_id"],"e.status"=>["elt","2"]])->sum("d.money");
        //可报销金额 = 总成本(初始成本+成本调整) - 已报销金额
        $data["expence_money"] = bcsub($data['crm_oeseng'],$data["expence_used_money"],2);
        
        
        
        // 追回金额
        // $recover_money=db("crm_finance")->where(["order_type"=>"退款","contract_id"=>$data['contract_id'],"check_status"=>2])->sum("recover_money");
        // // $expence_money = bcsub($expence_money,$crm_oeseng,2);
        // // var_dump($expence_money);exit;
        // $data["expence_money"] = bcsub($expence_money,$expence_used_money,2);
        // // 已报销金额 = 累计报销金额 - 退款追回金额
        // $data["expence_used_money"] = bcsub($expence_used_money,$recover_money,2);


        /*------------------回款、业绩、尾款扣除退款金额----------------------*/
        

        // 核定成本=现有金额（回款单核定成本+成本调整增减成本）-退回成本（退款金额-退回业绩）
        // 计算退回成本
        // $refund_oeseng = bcadd($refund_money,$calculate,2);
        
        // $hsOeseng = bcsub($moneyInfo["hsOeseng"],$refund_oeseng,2);
        // //业绩
        // $performance=bcadd($data["performance"],$calculate,2);
        // $data["performance"] = bcsub($performance,$crm_oeseng,2);
        // // 核定成本
        // $data['crm_oeseng'] = bcadd($hsOeseng,$crm_oeseng,2);

        // 退款金额
        $data["refund_money"]=$refund_money;
        
        $data["arrears"]=bcadd($data["arrears"],$refund_money,2);
        $datas=$data["receivablesMoney"];
        $datas["lasahmMoney"]=bcsub($datas["lasahmMoney"],$refund_money,2);

        
        $data["receivablesMoney"]=$datas;
        /*------------------回款、业绩、尾款扣除退款金额----------------------*/

        if (!empty($data['crm_grvgkz']) && (empty($data["monthly_agency_price"]) || $data["monthly_agency_price"] <= 0)) {
            $crm_month_price = bcdiv(($data['money'] - $data['crm_oeseng']) , $data['crm_grvgkz'],2);
            $data['crm_month_price'] = $crm_month_price;
        }
        //跟进提成
        $data['crm_field_price'] = \app\crm\model\Assignfield::where(["contract_id" => $param["id"]])->sum("money");
        //判断权限
        $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
        if ($data["check_status"] != 2 && $data["is_ok"] != 1) {
            //读权限
            $roPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'read');
            $rwPre = $userModel->rwPre($userInfo['id'], $data['ro_user_id'], $data['rw_user_id'], 'update');
            if (!in_array($data['owner_user_id'], $auth_user_ids) && !$roPre && !$rwPre && !in_array($userInfo["id"], $auth_user_ids)) {
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode(['code' => 102, 'error' => '无权操作']));
            }
        }
        if (!$data) {
            return resultArray(['error' => $contractModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 编辑合同
     * @param
     * @return
     * @author Michael_xu
     */
    public function update()
    {
        $contractModel = model('Contract');
        $userModel = new \app\admin\model\User();
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $param['create_user_id'] = $userInfo['id'];
        $param['owner_user_id'] = $userInfo['id'];
        /*----------------------------处理产品确认信息赋值start--------------------------------*/
        $param["crm_ddisob"]="新签";//只有记账订单才有续费单，其他订单默认都是新签单
        $param["state"]=1;//默认待捡取
        $fieldList=$param["product"][0]["fieldList"];//产品确认函信息
        if(isset($fieldList)){
            foreach ($fieldList as $list){
                if($list["title"]=="服务期数"){
                    $param["crm_grvgkz"]=$list["value"];
                }
                if($list["title"]=="服务公司"){
                    $param["name"]=$list["value"];
                }
                if($list["title"]=="记账单量"){
                    $param["crm_yfvcld"]=$list["value"];
                }
                if($list["title"]=="记账类型"){
                    $param["crm_ddisob"]=$list["value"];
                }
                if($list["title"]=="原销售"){
                    $param["crm_oonnxn"]=$list["value"];
                }
            }
        }
        /*----------------------------处理产品确认信息赋值end--------------------------------*/
        $dataInfo = $contractModel->getDataById($param['id']);
        if (!$dataInfo) {
            return resultArray(['error' => '数据不存在或已删除']);
        }
        if ($param["crm_oeseng"] > $param["total_price"]) {
            return resultArray(['error' => '核定成本不能大于订单金额']);
        }
        // if ($param["crm_oeseng"] < 0) {
        //     return resultArray(['error' => '核定成本不能为负']);
        // }
        //判断权限
        $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'update');
        //读写权限
        $rwPre = $userModel->rwPre($userInfo['id'], $dataInfo['ro_user_id'], $dataInfo['rw_user_id'], 'update');
        if (!in_array($dataInfo['owner_user_id'], $auth_user_ids) && !$rwPre) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }

        //已进行审批，不能编辑
        if (in_array($dataInfo['check_status'], ['2'])) {
            return resultArray(['error' => '当前订单状态已审批通过，不可编辑']);
        }
        //将合同审批状态至为待审核，提交后重新进行审批
        //审核判断（是否有符合条件的审批流）
        $examineFlowModel = new \app\admin\model\ExamineFlow();
        $examineStepModel = new \app\admin\model\ExamineStep();
        if (!$examineFlowModel->checkExamine($dataInfo['owner_user_id'], 'crm_contract')) {
            return resultArray(['error' => '暂无审批人，无法创建']);
        }
        //添加审批相关信息
        $examineFlowData = $examineFlowModel->getFlowByTypes($dataInfo['owner_user_id'], 'crm_contract');
        if (!$examineFlowData) {
            return resultArray(['error' => '无可用审批流，请联系管理员']);
        }
        $param['flow_id'] = $examineFlowData['flow_id'];
        //获取审批人信息
        if ($examineFlowData['config'] == 1) {
            //固定审批流
            $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $examineFlowData['flow_id'], 'crm_contract', 0, 0, 0);
            $next_user_ids = arrayToString($nextStepData['next_user_ids']) ?: '';
            $check_user_id = $next_user_ids ?: [];
            $param['order_id'] = 1;
        } else {
            $check_user_id = $param['check_user_id'] ? ',' . $param['check_user_id'] . ',' : '';
        }
        if (!$check_user_id) {
            return resultArray(['error' => '无可用审批人，请联系管理员']);
        }
        
        $param['check_user_id'] = is_array($check_user_id) ? ',' . implode(',', $check_user_id) . ',' : $check_user_id;
        $param['check_status'] = 0;

        //流程审批人
        // $flow_user_id = $examineFlowModel->getUserByFlow($examineFlowData['flow_id'], $dataInfo['owner_user_id']); 
        // $param['flow_user_id'] = $flow_user_id ? arrayToString($flow_user_id) : '';   
        $param['flow_user_id'] = '';

        $receivablesModel = model('Receivables');
        //审批主体详情
        $receivablesInfo = $receivablesModel->getDataByContractId($param['id']);
        
        if ($contractModel->updateDataById($param, $param['id'])) {
            //将审批记录至为无效
            $examineRecordModel = new \app\admin\model\ExamineRecord();
            $examineRecordModel->setEnd(['types' => 'crm_contract', 'types_id' => $param['id']]);

            $examineRecordModel = new \app\admin\model\ExamineRecord();
            $examineRecordModel->setEnd(['types' => 'crm_receivables', 'types_id' => $receivablesInfo['receivables_id']]);
            return resultArray(['data' => '编辑成功']);
        } else {
            return resultArray(['error' => $contractModel->getError()]);
        }
    }

    /**
     * 删除合同（逻辑删）
     * @param
     * @return
     * @author Michael_xu
     */
    public function delete()
    {
        $contractModel = model('Contract');
        $param = $this->param;
        $userInfo = $this->userInfo;

        if (!is_array($param['id'])) {
            $contract_id = [$param['id']];
        } else {
            $contract_id = $param['id'];
        }
        $delIds = [];
        $errorMessage = [];

        //数据权限判断
        $userModel = new \app\admin\model\User();
        $auth_user_ids = $userModel->getUserByPer('crm', 'business', 'delete');
        $adminTypes = adminGroupTypes($userInfo['id']);
        foreach ($contract_id as $k => $v) {
            $isDel = true;
            //数据详情
            $data = $contractModel->getDataById($v);
            if (!$data) {
                $isDel = false;
                $errorMessage[] = 'id为' . $v . '的合同删除失败,错误原因：' . $contractModel->getError();
                continue;
            }
            if (!in_array($data['owner_user_id'], $auth_user_ids)) {
                $isDel = false;
                $errorMessage[] = '名称为' . $data['name'] . '的合同删除失败,错误原因：无权操作';
                continue;
            }
            if (!in_array($data['check_status'], ['4']) && !in_array(1, $adminTypes)) {
                $isDel = false;
                $errorMessage[] = '名称为' . $data['name'] . '的合同删除失败,错误原因：请先撤销审核';
                continue;
            }
            $delIds[] = $v;
        }
        if ($delIds) {
            $data = $contractModel->delDatas($delIds);
            if (!$data) {
                return resultArray(['error' => $contractModel->getError()]);
            }
            actionLog($delIds, '', '', '');
        }
        if ($errorMessage) {
            return resultArray(['error' => $errorMessage]);
        } else {
            return resultArray(['data' => '删除成功']);
        }
    }

    /**
     * 合同转移
     * @param owner_user_id 变更负责人
     * @param is_remove 1移出，2转为团队成员
     * @param type 权限 1只读2读写
     * @return
     * @author Michael_xu
     */
    public function transfer()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $contractModel = model('Contract');
        $settingModel = model('Setting');
        $userModel = new \app\admin\model\User();
        $authIds = $userModel->getUserByPer(); //权限范围的user_id

        if (!$param['owner_user_id']) {
            return resultArray(['error' => '变更负责人不能为空']);
        }
        if (!$param['contract_id'] || !is_array($param['contract_id'])) {
            return resultArray(['error' => '请选择需要转移的合同']);
        }

        $is_remove = $param['is_remove'] == 2 ?: 1;
        $type = $param['type'] == 2 ?: 1;

        $data = [];
        $data['owner_user_id'] = $param['owner_user_id'];
        $data['update_time'] = time();

        $ownerUserName = $userModel->getUserNameById($param['owner_user_id']);
        $errorMessage = [];
        foreach ($param['contract_id'] as $contract_id) {
            $contractInfo = $contractModel->getDataById($contract_id);

            if (!$contractInfo) {
                $errorMessage[] = 'id:为' . $contract_id . '的合同转移失败，错误原因：数据不存在；';
                continue;
            }
            //权限判断
            if (!in_array($contractInfo['owner_user_id'], $authIds)) {
                $errorMessage[] = $contractInfo['name'] . '"转移失败，错误原因：无权限；';
                continue;
            }
            if (!in_array($contractInfo['check_status'], ['0', '1'])) {
                $errorMessage[] = $contractInfo['name'] . '"转移失败，错误原因：审批中或已有审核结果，无法转移；';
                continue;
            }
            $resContract = db('crm_contract')->where(['contract_id' => $contract_id])->update($data);
            if (!$resContract) {
                $errorMessage[] = $contractInfo['name'] . '"转移失败，错误原因：数据出错；';
                continue;
            }
            //修改记录
            updateActionLog($userInfo['id'], 'crm_contract', $contract_id, '', '', '将合同转移给：' . $ownerUserName);
        }
        if (!$errorMessage) {
            return resultArray(['data' => '转移成功']);
        } else {
            return resultArray(['error' => $errorMessage]);
        }
    }

    /**
     * 合同审核
     * @param
     * @return
     * @author Michael_xu
     */
    public function check()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $user_id = $userInfo['id'];
        $contractModel = model('Contract');
        $examineStepModel = new \app\admin\model\ExamineStep();
        $examineRecordModel = new \app\admin\model\ExamineRecord();
        $examineFlowModel = new \app\admin\model\ExamineFlow();
        $customerModel = model('Customer');

        $contractData = [];
        $contractData['update_time'] = time();
        $contractData['check_status'] = 1; //0待审核，1审核通中，2审核通过，3审核未通过
        //权限判断
        if (!$examineStepModel->checkExamine($user_id, 'crm_contract', $param['id'])) {
            return resultArray(['error' => $examineStepModel->getError()]);
        };
        //审批主体详情
        $dataInfo = $contractModel->getDataById($param['id']);
        $flowInfo = $examineFlowModel->getDataById($dataInfo['flow_id']);
        $is_end = 0; // 1审批结束

        $status = $param['status'] ? 1 : 0; //1通过，0驳回
        $checkData = [];
        $checkData['check_user_id'] = $user_id;
        $checkData['types'] = 'crm_contract';
        $checkData['types_id'] = $param['id'];
        $checkData['check_time'] = time();
        $checkData['content'] = $param['content'];
        $checkData['flow_id'] = $dataInfo['flow_id'];
        $checkData['order_id'] = $dataInfo['order_id'] ?: 1;
        $checkData['status'] = $status;

        if ($status == 1) {
            if ($flowInfo['config'] == 1) {
                //固定流程
                //获取下一审批信息
                $nextStepData = $examineStepModel->nextStepUser($dataInfo['owner_user_id'], $dataInfo['flow_id'], 'crm_contract', $param['id'], $dataInfo['order_id'], $user_id);
                $next_user_ids = $nextStepData['next_user_ids'] ?: [];
                $contractData['order_id'] = $nextStepData['order_id'] ?: '';
                if (!$next_user_ids) {
                    $is_end = 1;
                    //审批结束
                    $checkData['check_status'] = !empty($status) ? 2 : 3;
                    $contractData['check_user_id'] = '';
                } else {
                    //修改主体相关审批信息
                    $contractData['check_user_id'] = arrayToString($next_user_ids);
                }
            } else {
                //自选流程
                $is_end = $param['is_end'] ? 1 : '';
                $check_user_id = $param['check_user_id'] ?: '';
                if ($is_end !== 1 && empty($check_user_id)) {
                    return resultArray(['error' => '请选择下一审批人']);
                }
                $contractData['check_user_id'] = arrayToString($param['check_user_id']);
            }
            if ($is_end == 1) {
                $checkData['check_status'] = !empty($status) ? 2 : 3;
                $contractData['check_user_id'] = '';
                $contractData['check_status'] = 2;
            }
        } else {
            //审批驳回
            $is_end = 1;
            $contractData['check_status'] = 3;
            //将审批记录至为无效
            // $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
        }
        //2023-10-24 新增 start
        $contractData['calcuate'] = isset($param['calcuate']) ? $param['calcuate'] : 1;
        //2023-10-24 新增 end
        //已审批人ID
        $resContract['flow_user_id'] = stringToArray($dataInfo['flow_user_id']) ? arrayToString(array_merge(stringToArray($dataInfo['flow_user_id']), [$user_id])) : arrayToString([$user_id]);

        $resContract = db('crm_contract')->where(['contract_id' => $param['id']])->update($contractData);
        if ($resContract) {
            //审批记录
            $resRecord = $examineRecordModel->createData($checkData);
            //审核通过，相关客户状态改为已成交
            if ($is_end == 1 && !empty($status)) {
                //发送站内信
                $sendContent = '您的申请【' . $dataInfo['name'] . '】,' . $userInfo['realname'] . '已审核通过,审批结束';
                $resMessage = sendMessage($dataInfo['owner_user_id'], $sendContent, $param['id'], 1);

                $customerData = [];
                $customerData['deal_status'] = '已成交';
                $customerData['deal_time'] = time();
                db('crm_customer')->where(['customer_id' => $dataInfo['customer_id']])->update($customerData);
                //新增 start
                //同时审批回款记录
                $Receivables = Receivables::where(["contract_id" => $param['id'], "is_start" => 1])->whereIn("check_status", [0, 1,3])->find();
                if (!empty($Receivables)) {
                    $check_status = $param["check_status"];
                    $money = Receivables::where(["contract_id" => $param['id'], "check_status" => 0])->sum("money");
                    $number = $Receivables["number"] ?: '';
                    $code = "";
                    if ($param['status'] == 1) {
                        //审核通过
                        $check_status = 2;
                        /***********************将回款信息添加到财务表******************************/
                        //添加数据到财务表
                        $financeData=[
                            "create_user_id"=>$Receivables["create_user_id"],//发起人
                            "customer_id"=>$Receivables["customer_id"],//客户名称ID
                            "contract_id"=>$Receivables["contract_id"],//订单编号ID
                            "relation_id"=>$Receivables['receivables_id'],//关联ID、type为2回款时关联receivables_id，2则examine_id
                            "department"=>Db::name("crm_contract")->where(["contract_id"=>$Receivables["contract_id"]])->value("crm_kfhgfp"),//所属部门
                            "order_type"=>"回款",//订单类型（回款、退款、成本变更）
                            "money"=>$Receivables["money"],//回款金额
                            "calculate_month"=>date("Y-m",strtotime($Receivables["return_time"])),//业绩核算月份只针对回款和退款
                            "calculate_way"=>"正常核算",//业绩处理方式，只针对回款和退款(正常核算、暂不核算、业绩抵扣、提成退回)',
                            "created_time"=>date("Y-m-d H:i:s"),//(回款、成本变更、退款)时间
                            "check_status"=>2,//审核状态
                            "crm_oeseng"=>$Receivables["crm_oeseng"],//核定成本金额
                            "calculate" =>bcsub($Receivables["money"],$Receivables["crm_oeseng"],2),//业绩=回款金额-核定成本
                            "check_time"=>date("Y-m-d H:i:s"),//审核时间
                        ];
                        /***********************将回款信息添加到财务表******************************/
                        //2024-1-19 修改回款编号
                        if ($Receivables["crm_lasahm"] == "正常核算") {
                            $year=date("Y");
                            $month=date("m");
                            $financeNumber=Db::name("crm_finance")
                                ->where("YEAR(check_time)={$year} and MONTH(check_time)={$month} and calculate_way != '暂不核算'")
                                ->where(["department"=>$dataInfo["crm_kfhgfp"],"order_type"=>["in",["成本变更","退款","回款"]],"check_status"=>"2"])->count();
                            $financeNumber=$financeNumber>0?str_pad($financeNumber+1,4,"0",STR_PAD_LEFT):"0001";//财务编号
                            $number = substr($dataInfo["crm_kfhgfp"], 0, 1) . "-" . $year . "-" . $month . "-" . $financeNumber;
                            $code = $financeNumber;
                            $financeData["order_sn"]=$number;//财务表的编号
                            //修改合同尾款字段
                            \app\crm\model\Contract::where(["contract_id" => $dataInfo["contract_id"]])
                                ->setDec("arrears", $money);
                            //修改合同订单的核定成本
                            // \app\crm\model\Contract::where(["contract_id" => $dataInfo["contract_id"]])
                            //     ->setInc("crm_oeseng", $Receivables["crm_oeseng"]);
                        }
                        Db::name("crm_finance")->insert($financeData);
                    }
                    Receivables::where(["contract_id" => $param['id'],  "is_start" => 1])
                        ->update(["check_status" => $check_status, "code" => $code, "number" => $number]);
                }
                //计算期数
                $contract = \app\crm\model\Contract::where(["contract_id" => $param["id"]])->find();
                if (!empty($contract) && $contract["crm_wvgjii"] == "记账") {
                    $receivablesModel = model('Receivables');
                    $receivablesMoney = $receivablesModel->where(["contract_id" => $param["id"], "check_status" => 2])->sum("money");
                    $money = bcdiv($contract["total_price"], $contract["crm_grvgkz"], 2);
                    //$available=empty($contract["crm_grvgkz"])?0:ceil($receivablesMoney/$money);
                    $available = (empty($contract["crm_grvgkz"]) || $contract["crm_grvgkz"] <= 0) ? 0 : floor($receivablesMoney / $money);
                    $customerData['deal_status'] = '已成交';
                    $customerData['deal_time'] = time();
                    $contract->save(["available" => $available]);
                }
            } else {
                if ($status) {
                    //发送站内信
                    $sendContent = '您的申请【' . $dataInfo['name'] . '】,' . $userInfo['realname'] . '已审核通过';
                    $resMessage = sendMessage($dataInfo['owner_user_id'], $sendContent, $param['id'], 1);
                } else {
                    $sendContent = '您的申请【' . $dataInfo['name'] . '】,' . $userInfo['realname'] . '已审核拒绝,审核意见：' . $param['content'];
                    $resMessage = sendMessage($dataInfo['owner_user_id'], $sendContent, $param['id'], 1);
                    //新增 start
                    //同时审批回款记录
                    $Receivables = Receivables::where(["contract_id" => $param['id'], "is_start" => 1])->find();
                    if (!empty($Receivables)) {
                        Receivables::where(["contract_id" => $param['id'], "is_start" => 1])->update(["check_status" => 3, "remark" => $param['content']]);
                    }
                }
            }
            //2023-12-21 新增 ---start
            /*$accountingModel = model('Accounting');
            $price=$accountingModel->monthlyAgencyPrice($dataInfo["contract_id"]);
            \app\crm\model\Contract::where(["contract_id"=>$dataInfo["contract_id"]])->update(["monthly_agency_price"=>$price]);*/
            //2023-12-21 新增 ---end
            //新增 end
            return resultArray(['data' => '审批成功']);
        } else {
            return resultArray(['error' => '审批失败，请重试！']);
        }
    }

    /**
     * 合同撤销审核
     * @param
     * @return
     * @author Michael_xu
     */
    public function revokeCheck()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $user_id = $userInfo['id'];
        $contractModel = model('Contract');
        $examineRecordModel = new \app\admin\model\ExamineRecord();
        $customerModel = model('Customer');
        $userModel = new \app\admin\model\User();

        $contractData = [];
        $contractData['update_time'] = time();
        $contractData['check_status'] = 0; //0待审核，1审核通中，2审核通过，3审核未通过
        //审批主体详情
        $dataInfo = $contractModel->getDataById($param['id']);
        //权限判断(负责人或管理员)        
        if ($dataInfo['check_status'] == 2) {
            return resultArray(['error' => '已审批结束,不能撤销']);
        }
        if ($dataInfo['check_status'] == 4) {
            return resultArray(['error' => '无需撤销']);
        }
        $admin_user_ids = $userModel->getAdminId();
        if ($dataInfo['owner_user_id'] !== $user_id && !in_array($user_id, $admin_user_ids)) {
            return resultArray(['error' => '没有权限']);
        }

        $is_end = 0; // 1审批结束
        $status = 2; //1通过，0驳回, 2撤销
        $checkData = [];
        $checkData['check_user_id'] = $user_id;
        $checkData['types'] = 'crm_contract';
        $checkData['types_id'] = $param['id'];
        $checkData['check_time'] = time();
        $checkData['content'] = $param['content'];
        $checkData['flow_id'] = $dataInfo['flow_id'];
        $checkData['order_id'] = $dataInfo['order_id'];
        $checkData['status'] = $status;

        $contractData['check_status'] = 4;
        $contractData['check_user_id'] = '';
        $examineData['flow_user_id'] = '';
        $resContract = db('crm_contract')->where(['contract_id' => $param['id']])->update($contractData);
        if ($resContract) {
            //将审批记录至为无效
            // $examineRecordModel->setEnd(['types' => 'crm_contract','types_id' => $param['id']]);
            //审批记录
            $resRecord = $examineRecordModel->createData($checkData);

            
            // 撤回回款审批
            $receivablesModel = model('Receivables');
            $examineStepModel = new \app\admin\model\ExamineStep();
            $examineRecordModel = new \app\admin\model\ExamineRecord();

            $receivablesData = [];
            $receivablesData['update_time'] = time();
            $receivablesData['check_status'] = 0; //0待审核，1审核通中，2审核通过，3审核未通过

            //审批主体详情
            $dataInfo = $receivablesModel->getDataByContractId($param['id']);

            //撤回时同步财务表的审核状态
            if($dataInfo["receivables_id"]){
                db("crm_finance")->where([
                    "relation_id"  => $dataInfo["receivables_id"],
                    "order_type"   => "回款",
                    "check_status" => ["in",["0","1"]]
                ])->update([
                    "check_status" => 4
                ]);
            }
            //权限判断(创建人或负责人或管理员)
            if ($dataInfo['check_status'] == 2) {
                return resultArray(['error' => '已审批结束,不能撤销']);   
            } 
            if ($dataInfo['check_status'] == 4) {
                return resultArray(['error' => '无需撤销']);   
            }
              
            $is_end = 0; // 1审批结束
            $status = 2; //1通过，0驳回, 2撤销
            $checkData = [];
            $checkData['check_user_id'] = $user_id;
            $checkData['types'] = 'crm_receivables';
            $checkData['types_id'] = $dataInfo["receivables_id"];
            $checkData['check_time'] = time();
            $checkData['content'] = $param['content'];
            $checkData['flow_id'] = $dataInfo['flow_id'];
            $checkData['order_id'] = $dataInfo['order_id'];
            $checkData['status'] = $status;
            
            $receivablesData['check_status'] = 4;
            $receivablesData['check_user_id'] = '';
            $receivablesData['flow_user_id'] = '';
            $resReceivables = db('crm_receivables')->where(['receivables_id' => $dataInfo["receivables_id"]])->update($receivablesData);
            if ($resReceivables) {
                //将审批记录至为无效
                // $examineRecordModel->setEnd(['types' => 'crm_receivables','types_id' => $param['id']]);
                //审批记录
                $resRecord = $examineRecordModel->createData($checkData);
                return resultArray(['data' => '撤销成功']);            
            } else {
                return resultArray(['error' => '撤销失败，请重试！']); 
            }
        } else {
            return resultArray(['error' => '撤销失败，请重试！']);
        }
    }

    /**
     * 相关产品
     * @param
     * @return
     * @author Michael_xu
     */
    public function product()
    {
        $productModel = model('Product');
        $contractModel = model('Contract');
        $userModel = new \app\admin\model\User();
        $param = $this->param;
        $userInfo = $this->userInfo;
        if (!$param['contract_id']) {
            return resultArray(['error' => '参数错误']);
        }
        $contractInfo = db('crm_contract')->where(['contract_id' => $param['contract_id']])->find();
        //判断权限
        $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
        //读写权限
        $roPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'read');
        $rwPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'update');

        if (!in_array($contractInfo['owner_user_id'], $auth_user_ids) && !$roPre && !$rwPre && !in_array($userInfo["id"], $auth_user_ids)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }

        $dataList = db('crm_contract_product')->where(['contract_id' => $param['contract_id']])->select();
        foreach ($dataList as $k => $v) {
            $where = [];
            $where['product_id'] = $v['product_id'];
            $productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
            $category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
            $dataList[$k]['name'] = $productInfo['name'] ?: '';
            $dataList[$k]['category_id_info'] = $category_name ?: '';
        }
        $list['list'] = $dataList ?: [];
        $list['total_price'] = $contractInfo['total_price'] ?: '0.00';
        $list['discount_rate'] = $contractInfo['discount_rate'] ?: '0.00';
        return resultArray(['data' => $list]);
    }

    //新增

    /**
     * 相关产品的确认函
     * @param
     * @return
     * @author Michael_xu
     */
    public function confirmation()
    {
        $productModel = model('Product');
        $contractModel = model('Contract');
        $userModel = new \app\admin\model\User();
        $param = $this->param;
        $userInfo = $this->userInfo;
        if (!$param['contract_id']) {
            return resultArray(['error' => '参数错误']);
        }
        $contractInfo = db('crm_contract')->where(['contract_id' => $param['contract_id']])->find();
        //判断权限
        $auth_user_ids = $userModel->getUserByPer('crm', 'contract', 'read');
        //读写权限
        $roPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'read');
        $rwPre = $userModel->rwPre($userInfo['id'], $contractInfo['ro_user_id'], $contractInfo['rw_user_id'], 'update');
        if (!in_array($contractInfo['owner_user_id'], $auth_user_ids) && !$roPre && !$rwPre) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }
        $dataList = db('crm_contract_product')->where(['contract_id' => $param['contract_id']])->select();
        foreach ($dataList as $k => $v) {
            $where = [];
            $where['product_id'] = $v['product_id'];
            $productInfo = db('crm_product')->where($where)->field('name,category_id')->find();
            $category_name = db('crm_product_category')->where(['category_id' => $productInfo['category_id']])->value('name');
            $dataList[$k]['name'] = $productInfo['name'] ?: '';
            $dataList[$k]['category_id_info'] = $category_name ?: '';
        }
        $list['list'] = $dataList ?: [];
        $list['total_price'] = $contractInfo['total_price'] ?: '0.00';
        $list['discount_rate'] = $contractInfo['discount_rate'] ?: '0.00';
        return resultArray(['data' => $list]);
    }

    /**
     * 分配外勤
     * @return
     * @author Michael_xu
     */
    public function assign()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $assignfieldModel = model('Assignfield');
        /*$param['contract_id']=12;
        $userInfo['id']=3;
        $param['user_id']=[4,5];*/
        if (!$param['user_id']) {
            return resultArray(['error' => '请先选择外勤']);
        }
        $admin_user_ids = $param['user_id'];
        if (!$param['contract_id']) {
            return resultArray(['error' => '订单id为空']);
        }
        if (!$param['name']) {
            return resultArray(['error' => '标题不能为空']);
        }
        $group = db('admin_access')->where(['user_id' => $userInfo["id"], "group_id" => "32"])->find();
        if (empty($group)) return resultArray(['error' => "只有管家才能分配外勤"]);


        //权限判断
        $contractModel = new \app\crm\model\Contract();
        $dataInfo = $contractModel->where(['contract_id' => $param["contract_id"]])->find();
        //判断权限
        //判断管家只能操作自己拾取的工单
        if ($dataInfo["state"] == 1) {
            return resultArray(['error' => "订单'" . $dataInfo['name'] . "'操作失败，错误原因：订单未捡取"]);
        }
        if (!empty($group) && $dataInfo["butler_id"] != $userInfo["id"]) {
            return resultArray(['error' => "订单'" . $dataInfo['name'] . "'操作失败，错误原因：您未拾取该订单，不能操作该订单"]);
        }
        //新增 lina end
        /*if($dataInfo["check_status"]!=2){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单状态错误"]);
        }*/
        if ($dataInfo["is_ok"] == 1) {
            return resultArray(['error' => "订单'" . $dataInfo['name'] . "'操作失败，错误原因：订单已完结"]);
        }
        $assignfield_data = [];
        foreach ($admin_user_ids as $k => $v) {
            $assignfield_data[$k] = [
                "admin_user_id" => $v,
                "butler_id" => $userInfo["id"],
                "butler_time" => time(),
                "contract_id" => $param["contract_id"],
                "name" => $param["name"],
                "money"=>$param["money"],
                "remark" => $param["remark"] ?: '',
            ];
        }
        $res = [];
        Db::startTrans();
        try {
            /*$assignfield_data=[
                "admin_user_id"=>$admin_user_ids,
                "butler_id"=>$userInfo["id"],
                "butler_time"=>time(),
                "contract_id"=>$param["contract_id"],
                "name"=>$param["name"],
                "remark"=>$param["remark"]?:'',
            ];*/
            if (!empty($assignfield_data)) {
                $res = $assignfieldModel->assign($assignfield_data);
            }
            db("crm_contract")->where(["contract_id"=>$param["contract_id"]])->update(["update_time"=>time()]);//更新操作时间
            $dataInfo->save(["state" => 3]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($res) {
            return resultArray(['data' => '分配成功']);
        }
    }


}
